package com.ruoyi.mine.service.Impl;


import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.backendEnum.MineException;
import com.ruoyi.mine.mapper.MinesMapper;
import com.ruoyi.mine.pojo.Mine;
import com.ruoyi.mine.service.MinesService;
import com.ruoyi.mine.vo.MinesInfoByProvinceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MinesServiceImpl implements MinesService {

    @Autowired
    private MinesMapper minesMapper;

    @Override
    public void add(Mine mine) {
        minesMapper.add(mine);
    }

    @Override
    public void delete(String mineId) {
        if (minesMapper.getMineCount(mineId) == 0){
            throw new ServiceException(MineException.MINE_DATA_NOT_EXIST);
        }
        minesMapper.delete(mineId);
    }

    @Override
    public void update(Mine mine) {
        if (minesMapper.getMineCount(mine.getMineId()) == 0){
            throw new ServiceException(MineException.MINE_DATA_NOT_EXIST);
        }
        minesMapper.update(mine);
    }

    @Override
    public List<Mine> search(Mine mine) {
        List<Mine> mineList = minesMapper.search(mine);
//        if (mineList.isEmpty()){
//            throw new ServiceException(MineException.MINE_DATA_NOT_FOUND);
//        }
        return mineList;
    }

    @Override
    public List<Mine> searchAll() {
        return minesMapper.searchAll();
    }

    @Override
    public List<MinesInfoByProvinceVO> searchByProvince() {

        List<Mine> mines = minesMapper.searchAll();
        List<MinesInfoByProvinceVO> mineslist = mines.stream()
                .collect(Collectors.groupingBy(Mine::getMineProvince)) // 按省份分组
                .entrySet().stream()
                .map(entry -> new MinesInfoByProvinceVO(entry.getKey(), entry.getValue())) // 构造 VO，传入当前省份和对应的矿坑列表
                .collect(Collectors.toList());
        return mineslist;
    }
}
